/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package assignment1;

import java.util.StringTokenizer;
import java.util.Vector;

/**
 *
 * @author cjaramillo
 */
public class Antecedent {
    
    public enum Combiner{AND,OR};
    
    Vector<Expression>m_expressions;
    Vector<Combiner>m_combiners;
    
    Antecedent()
    {
        m_expressions = new Vector<Expression>();
        m_combiners = new Vector<Combiner>();
    }
    
    boolean evaluate(Database database) {
        boolean retVal = false;
        retVal = m_expressions.elementAt(0).evaluate(database);
        for(int i=1; i<m_expressions.size();i++)
        {
            switch(m_combiners.elementAt(i-1))
            {
                case AND:
                    retVal = (retVal && m_expressions.elementAt(i).evaluate(database));
                    break;
                case OR:
                    retVal = (retVal || m_expressions.elementAt(i).evaluate(database));
                    break;
            }
        }
        return retVal;
    }
    
    public void populateFromString(String antecedent)
    {
        StringTokenizer tokenizer = new StringTokenizer(antecedent, " ");
        String ifString = tokenizer.nextToken();
        String currentExpression = new String();
        while(tokenizer.hasMoreTokens())
        {
            String currentToken = tokenizer.nextToken();
            if(currentToken.equals("OR"))
            {
                Expression newExpression = new Expression();
                newExpression.populateFromString(currentExpression);
                m_expressions.add(newExpression);
                m_combiners.add(Combiner.OR);
                currentExpression = new String();
            }
            else if(currentToken.equals("AND"))
            {
                Expression newExpression = new Expression();
                newExpression.populateFromString(currentExpression);
                m_expressions.add(newExpression);
                m_combiners.add(Combiner.AND);
                currentExpression = new String();
            }
            else
            {
                currentExpression = currentExpression + " " + currentToken;
            }
        }
        Expression newExpression = new Expression();
        newExpression.populateFromString(currentExpression);
        m_expressions.add(newExpression);
    }
}